<template>
  <!-- 经销商区域经理维护 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="topFilterRef"
      :list="topFilterInit"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :isSelectColumn="isSelectColumn"
      :params="flterValue"
      :datakey="'records'"
      columnsRef="origin_personnelInfo_areaMaintain_index_01"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <!--el-button size="small" type="primary" icon="el-icon-plus" @click="dialogAddHandle()">新增</el-button-->
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel()"
        >下载</el-button>
      </template>
    </FilterTable>
    <Drawer
      :visible.sync="visible"
      title="区域经理人员选择"
      :width="800"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <addDialog v-model="initData" @close="dialogClose" />
    </Drawer>
    <!-- 区域经理弹窗 -->
    <BaseDialog
      title="人员选择"
      width="700px"
      destroyOnClose
      :visible.sync="visiblePersonnel"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <personnel-madal ref="personnelDialog" selectType="single" @close="closePersonnel" />
    </BaseDialog>
    <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-madal
        ref="addDialogRef"
        selectType="multiple"
        v-model="initDealerData"
        @close="closeDealer"
      />
    </BaseDialog>
  </div>
</template>
<script>
import personnelMadal from '@/pages/cms-common/user';
import dealerMadal from '@/pages/cms-common/dealerdata';
import addDialog from './addDialog';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { searchRegionalManager, exportExcel } from '@/api/cms-api/origin/personnelInfo/areaMaintain';
import { getRegion, getCommunity } from '@/api/cms-common/dealerdata/index';
export default {
  components: {
    addDialog,
    dealerMadal,
    personnelMadal
  },
  mixins: [dictionary],
  data() {
    return {
      // dealerList:[],
      appName:'qyjl',//经销商区域经理维护功能
      dealerCode: '',
      dealerName: '',
      visible: false,
      visibleDealer: false,
      isSelectColumn: false,
      initData: {},
      handleType: '',
      formData: {},
      topFilterInit: this.topFilterInitFun(),
      visiblePersonnel: false, //人员弹窗开关
      initDealerData: {}, //经销商弹窗参数
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchApi: searchRegionalManager,
      exportLoading: false,
      userId: '',
      userName: ''
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getDeptData();
  },
  methods: {
    //搜索数据
    topFilterInitFun() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '事业部',
        //   fieldName: 'deptId',
        //   initialValue: '',
        //   style: { width: '200px' },
        //   placeholder: '请选择...',
        //   itemList: [],
        //   change: val => {
        //     this.changeDeptSelect(val);
        //   }
        // },
        // { type: 'INPUT', label: '区域经理姓名', fieldName: 'userName', placeholder: '请输入', initialValue: '' },
        {
          type: 'INPUT',
          label: '区域经理姓名',
          fieldName: 'userName',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button slot="append" icon="el-icon-search" onClick={() => this.personnelHandle()}></el-button>
                <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearPersonnelHandle()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'dealerName',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button slot="append" icon="el-icon-search" onClick={() => this.dealerHandle()}></el-button>
                <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearDealerHandle()}></el-button>
              </div>
            );
          }
        }
        // {
        //   type: 'SELECT',
        //   label: '办事处',
        //   fieldName: 'officeId',
        //   // initialValue: '',
        //   style: { width: '200px' },
        //   placeholder: '请选择...',
        //   itemList: []
        // },
        // { type: 'SELECT', label: '状态', fieldName: 'status', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1003') }
      ];
    },
    //获取事业部下拉列表数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterInit[0].itemList = res.data.map(x => ({ value: x.id, text: x.orgName }));
      }
    },
    //事业部下拉改变执行方法，级联查询该事业部下的办事处
    async changeDeptSelect(deptId) {
      //清空办事处数据
      this.topFilterInit[3].initialValue = '';
      this.topFilterInit[3].itemList = [];
      //查询事业部下的办事处
      if (deptId) {
        const res = await getCommunity(deptId);
        if (res.resultCode === 200) {
          this.topFilterInit[3].itemList = res.data.map(x => ({ value: x.id, text: x.orgName }));
        }
      }
    },
    //搜索获取数据
    changeHandle(val) {
      if (!val.dealerName) {
        this.dealerCode = '';
      }
      if (!val.userName) {
        this.userId = '';
      }
      this.flterValue = Object.assign({}, val, { dealerCode: this.dealerCode, userId: this.userId });
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.dialogHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },

        // {
        //   title: '状态',
        //   dataIndex: 'status',
        //   sorter: true,
        //   render: props => {
        //     //编码转汉字
        //     return <span>{this.createDictText(props.row.status, '1003')}</span>;
        //   }
        // },
        /*       { title: '事业部', dataIndex: 'deptName', sorter: true ,width:200},
        { title: '办事处', dataIndex: 'officeName', sorter: true },
*/
        { title: '区域经理代码', dataIndex: 'userCode', sorter: true },
        { title: '区域经理姓名', dataIndex: 'userName', sorter: true },
        {
          title: '性别',
          dataIndex: 'gender',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        { title: '身份证号码', dataIndex: 'certificateId', sorter: true },
        { title: '手机', dataIndex: 'mobilePhone', sorter: true },
        { title: '邮箱', dataIndex: 'eMail', sorter: true },
        {
          title: '下属经销商数量',
          dataIndex: 'dealerTotalNum',
          sorter: true
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          dateFormat: 'yyyy-MM-dd',
          sorter: true
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          dateFormat: 'yyyy-MM-dd',
          sorter: true
        }
      ];
    },
    // 人员打开窗口 -传数据
    personnelHandle() {
      this.visiblePersonnel = true;
    },
    // 清空人员数据
    clearPersonnelHandle() {
      //清空数据内容
      this.userId = '';
      this.userName = '';

      //清空人员名称
      this.topFilterInit.find(item => item.fieldName === 'userName').initialValue = '';
    },
    // 人员关闭窗口 -返回数据
    closePersonnel(data) {
      if (data.type != 'close' && data.data && data.data.length > 0) {
        //清空数据内容
        this.userId = '';
        this.userName = '';

        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接用户ID
          if (this.userId == '') {
            this.userId = x.userId;
          } else {
            this.userId += ',' + x.userId;
          }

          //使用逗号分隔拼接用户姓名
          if (this.userName == '') {
            this.userName = x.employeeName;
          } else {
            this.userName += ',' + x.employeeName;
          }
        });
        //显示人员名称
        // this.topFilterInit[1].initialValue = this.userName;
        this.topFilterInit.find(item => item.fieldName === 'userName').initialValue = this.userName;
      }
      //关闭弹窗
      this.visiblePersonnel = data.visible;
    },
    // 经销商打开窗口 -传数据
    dealerHandle() {
      this.initDealerData = {
        excludeBigCustomer: false, //是否查询大客户经销商，如果查询 true，不查询 false
        id: 1001
      };
      this.visibleDealer = true;
    },
    // 清空经销商数据
    clearDealerHandle() {
      //清空数据内容
      this.dealerCode = '';
      this.dealerName = '';
      //清空人员名称
      this.topFilterInit.find(item => item.fieldName === 'dealerName').initialValue = '';
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      if (data.data && data.data.length > 0) {
        //清空数据内容
        this.dealerCode = '';
        this.dealerName = '';
        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接经销商ID
          if (this.dealerCode == '') {
            this.dealerCode = x.dealerCode;
          } else {
            this.dealerCode += ',' + x.dealerCode;
          }

          // this.dealerList.push(x.dealerId);
          //使用逗号分隔拼接经销商名称
          if (this.dealerName == '') {
            this.dealerName = x.dealerName;
          } else {
            this.dealerName += ',' + x.dealerName;
          }
        });
        //显示经销商名称
        // this.topFilterInit[2].initialValue = this.dealerName;
        this.topFilterInit.find(item => item.fieldName === 'dealerName').initialValue = this.dealerName;
      }
      //关闭弹窗
      this.visibleDealer = data.visible;
    },
    //新增
    dialogAddHandle() {
      this.visible = true;
      const pram = {
        type: 'add',
        rowData: null
      };
      this.initData = pram;
    },
    //详情
    dialogHandle(row) {
      this.visible = true;
      const pram = {
        type: 'edit',
        rowData: row
      };
      this.initData = pram;
    },
    //关闭详情
    dialogClose(data) {
      this.visible = false;
      if (data.type === 'refresh') {
        // 重新加载
        this.flterValue = { ...this.flterValue };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //导出
    async exportExcel() {
      let r = await this.$refs.topFilterRef.GET_FORM_DATA();
      let p = {};
      if (r != null && r.length > 1) {
        p = r[1];
      }
      this.exportLoading = true;
      exportExcel(p).then(res => {
        exportExcelFile(res.data, '经销商区域经理');
        this.exportLoading = false;
      });
    }
  }
};
</script>

<style>
.cover-container {
  width: 70vw !important;
}
</style>

<style lang="less" scoped>
</style>
